package cn.walls1717.juc.future;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * CompletableFuture的创建测试
 *
 * CompletableFuture最好通过静态方法创建，不要通过直接new创建。<br>
 * 它有两大类，四个静态方法：<br><br>
 *
 * runAsync() 无返回值<br>
 * <ul>
 *   <li>runAsync(Runnable runnable) 使用默认线程池创建</li>
 *   <li>runAsync(Runnable runnable, Executor executor) 使用指定线程池创建</li>
 * </ul>
 *
 * supplyAsync() 有返回值<br>
 * <ul>
 *   <li>supplyAsync(Supplier<U> supplier)</li>
 *   <li>supplyAsync(Supplier<U> supplier, Executor executor)</li>
 * </ul>
 *
 * @author walls1717
 * @create 2022/12/09 12:57
 **/
@Slf4j
public class CompletableFutureBuilderDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        /*
         * 无返回值方法 runAsync()
         * 这个方法有两个重载方法，一个不用指定线程池使用默认线程池，另一个可以传入我们自己的线程池。
         */
        /*CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            log.info(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor);*/

        /*
         * 有返回值
         * 重载的两个方法与runAsync()相同
         */
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            log.info(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "supplyAsync return";
        }, executor);

        log.info(String.valueOf(future.get()));
    }
}
